// JWT
const crypto = require('crypto')

const solt = 'Wivwiv%03qif093qj@1113'

function getter(payload) {
  if (typeof payload === 'object') {
    payload = JSON.stringify(payload)
  }
  return crypto.createHmac('sha256', payload)
    .update(solt)
    .digest('hex')
}

function expireCheck(expire) {
  return (expire - Date.now()) > 0
}

const _token = {
  user: {
    _id: '',
    username: '',
  },
  expire: Number,
  token: String,
}

function AuthTokenMiddleware(req, res, next) {
  let token = req.get("token") || 'e30='
  token = Buffer(token, 'base64').toString('utf-8')
  try {
    token = JSON.parse(token)
    const user = token.user
    if (!user || !user.username) {
      return res.hasError(401, '认证失败,登录用户不存在')
    }
    if (!token.expire || !expireCheck(token.expire)) {
      return res.hasError(401, '登录超时,请重新登录')
    }
    const _token = token.token || ''
    delete token['token']
    if (getter(token) !== _token) {
      return res.hasError(401, '登录凭证无效: 被篡改')
    }
    req.user = user
    next()
  } catch (e) {
    res.hasError(401, '认证失败,登录凭证无效', e)
  }
}


module.exports = {
  auth: AuthTokenMiddleware,
  getter: getter,
}